/*
 * @Author: 徐建辰
 * @Date: 2022-06-01 10:02:35
 * @LastEditTime: 2022-06-01 14:22:39
 * @LastEditors: 徐建辰
 * @Description: 文件导出，分情况   1:后端返回二进制流  2:导出json数据到excel
 */
import XLSX from 'xlsx'
import {saveAs} from 'file-saver'
import {sheetFromArrayOfArrays, generateArray, s2ab} from '@/utils/excel'

/**
 * @description: 后端返回二进制流的时候, 直接导出
 * @param {*String} 导出的文件名
 * @param {*Object/Array} 需要导出的数据(必须是二进制流)
 */
 export function excelToExcel(filename = `${'测试的'}.xlsx`, data) {
  let _val = data
  let blob = new Blob([_val])
  let downloadElement = document.createElement('a')
  let href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  downloadElement.download = filename
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement) //下载完成移除元素
  window.URL.revokeObjectURL(href) //释放掉blob对象
}

/**
 * @description: 导出json数据到excel
 * @param {*Array} 表头
 * @param {*Array} 需要导出的数据(必须是二维数组)
 * @param {*String} 导出的文件名
 */
 export function exportJsonToExcel(th, jsonData, defaultTitle = '列表', autoWidth = true) {
  let data = jsonData
  data.unshift(th)
  const ws_name = 'SheetJS'
 
  const wb = new Workbook()
  const ws = sheetFromArrayOfArrays(data)
  // 自适应宽度处理
  if (autoWidth) {
    // 设置worksheet每列的最大宽度
    const colWidth = data.map(row => row.map(val => {
      // 先判断是否为null/undefined
      if (val == null) {
        return {wch: 10}
      } else if (val.toString().charCodeAt(0) > 255) { // 再判断是否为中文
        return {wch: val.toString().length * 2}
      } else {
        return {wch: val.toString().length}
      }
    }))
    // 以第一行为初始值
    let result = colWidth[0]
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]['wch'] < colWidth[i][j]['wch']) {
          result[j]['wch'] = colWidth[i][j]['wch']
        }
      }
    }
    ws['!cols'] = result
  }
  // 将工作表添加到工作簿
  wb.SheetNames.push(ws_name)
  wb.Sheets[ws_name] = ws
  
  const wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  })
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), defaultTitle + ".xlsx")
}

/**
 * @description: 导出table数据到excel
 * @param {*Array} 表头
 * @param {*Array} 需要导出的数据(必须是二维数组)
 * @param {*String} 导出的文件名
 */
 export function exportTableToExcel(id) {
  const theTable = document.getElementById(id)
  const oo = generateArray(theTable)
  const ranges = oo[1]
 
  /* 源数据 */
  var data = oo[0]
  var ws_name = "SheetJS"
 
  const wb = new Workbook()
  const ws = sheetFromArrayOfArrays(data)
 
  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges
 
  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws
 
  const wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  })
 
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}